package com.wolfalpha.utron.activity;

import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormal2Activity;
import com.wolfalpha.utron.adapter.ItemInformationCommentAdapter;
import com.wolfalpha.utron.app.AppConfig;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.Information;
import com.wolfalpha.utron.bean.InformationComment;
import com.wolfalpha.utron.service.InformationService;
import com.wolfalpha.utron.service.impl.InformationServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.InputTools;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.ScrollXListView;
import com.wolfalpha.utron.view.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 资讯详情界面
 * <p/>
 * Created by luodon on 15/8/26.
 */
public class InformationDetailActivity extends BaseNormal2Activity implements AdapterView.OnItemClickListener, View.OnClickListener, OnItemLongClickListener, XListView.IXListViewListener {

    private ScrollXListView lvComments;        //评论列表控件

    private WebView wbContent;          //文本内容

    private TextView tvTitle;           //标题
    private TextView tvFrom;            //来源
    private TextView tvTime;            //时间

    private TextView tvPraise;          //点赞
    private TextView tvDisPraise;       //反对

    private EditText etCConetent;       //回复内容
    private Button btnSend;             //标题
    private CheckBox ivCollect;        //收藏


    private LinearLayout llInfo;          //内容布局
    private RelativeLayout root;          //根布局


    private ItemInformationCommentAdapter commentAdapter;//资讯适配器
    private List<InformationComment> comments = new ArrayList<InformationComment>();
    private UMSocialService mController;
    private InformationService informationService;  //服务

    private int infoId;             //资讯ID
    Information information = null;


    private final int LOAD_FINISH = 1;          //网页加载完成
    private final int CLICK_COMMENT = 2;        //点击评论者
    private final int START_REFRESH = 3;        //刷新
    private final int IPUT_SHOW = 4;            //显示输入框
    private final int IPUT_DISMISS = 5;         //关闭输入法

    private int toUserId = 0;                   //回复对象ID

    private boolean inputIsShowing = false;     //输入法显示状态

    private ScrollView scInfo;                  //滑动内容

    private int listY = 0;                          //listView的Y坐标

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_FINISH:
                    // setListViewHeightBasedOnChildren(lvComments);
                    tvTitle.setText(information.getTitle());
                    tvTime.setText(StringUtils.friendly_time(StringUtils.TimeStamp2Date(information.getTime() * 1000)));
                    tvFrom.setText("来自: " + information.getFrom());
                    tvPraise.setText(String.valueOf(information.getGrates()));
                    tvDisPraise.setText(String.valueOf(information.getUseless()));
                    ivCollect.setChecked(information.getCollected() == 1);
                    // 设置分享内容
                    mController.setShareContent("#" + information.getTitle() + "#" + information.getContent() + "@优创会");
                    break;
                case CLICK_COMMENT:
                    etCConetent.setText("@" + msg.obj.toString() + "//");
                    InputTools.KeyBoard(etCConetent, "open");
                    break;
                case IPUT_SHOW:
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(0, 0, 0, msg.arg1);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    llInfo.setLayoutParams(layoutParams);
                    llInfo.invalidate();

                    if (listY == 0) {
                        int[] location = new int[2];
                        lvComments.getLocationInWindow(location);
                        int[] location1 = new int[2];
                        wbContent.getLocationInWindow(location1);
                        listY = location[1] - location1[1];
                    }
                    scInfo.smoothScrollTo(0, listY);
                    break;
                case IPUT_DISMISS:
                    RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams1.setMargins(0, 0, 0, 0);
                    layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    llInfo.setLayoutParams(layoutParams1);
                    llInfo.invalidate();
                    scInfo.smoothScrollTo(0, listY);
                    break;
            }
        }
    };
    private Drawable disPraiseSelected;
    private Drawable disPraiseNormal;
    private Drawable praiseSelected;
    private Drawable praiseNormal;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || !bundle.containsKey("infoId")) {
            finish();
        } else {
            infoId = bundle.getInt("infoId");
        }

        setContentView(R.layout.activity_information_detail);
        informationService = new InformationServiceImpl();
        // 首先在您的Activity中添加如下成员变量
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
        // 设置分享内容
        mController.setShareContent("");
        // 设置分享图片, 参数2为图片的url地址
        //mController.setShareMedia(new UMImage(MainActivity.this,
        //        "http://www.umeng.com/images/pic/banner_module_social.png"));
        // 设置分享图片，参数2为本地图片的资源引用
        //mController.setShareMedia(new UMImage(getActivity(), R.drawable.icon));
        // 设置分享图片，参数2为本地图片的路径(绝对路径)
        //mController.setShareMedia(new UMImage(getActivity(),
        //                                BitmapFactory.decodeFile("/mnt/sdcard/icon.png")));

        // 设置分享音乐
        //UMusic uMusic = new UMusic("http://sns.whalecloud.com/test_music.mp3");
        //uMusic.setAuthor("GuGu");
        //uMusic.setTitle("天籁之音");
        // 设置音乐缩略图
        //uMusic.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
        //mController.setShareMedia(uMusic);

        // 设置分享视频
        //UMVideo umVideo = new UMVideo(
        //          "http://v.youku.com/v_show/id_XNTE5ODAwMDM2.html?f=19001023");
        // 设置视频缩略图
        //umVideo.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
        //umVideo.setTitle("友盟社会化分享!");
        //mController.setShareMedia(umVideo);

        intiView();
        initListeners();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private int page = 1;

    /**
     * 加载列表的数据
     */
    private void loadData() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                if (infoId < 0) {
                    return;
                }
                information = informationService.getDetail(infoId);
                if (information != null) {
                    handler.sendEmptyMessage(LOAD_FINISH);
//                    comments = information.getComment();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            wbContent.post(new Runnable() {
                                @Override
                                public void run() {
//                                    wbContent.loadUrl(information.getContent());
                                    wbContent.loadData(getHtmlData(information.getContent()), "text/html; charset=utf-8", "utf-8");
                                }
                            });
                        }
                    });
                }
            }
        });
        onRefresh();
    }

    /**
     * 刷新评论
     */
    @Override
    public void onRefresh() {
        page = 1;
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                if (infoId < 0) {
                    return;
                }
                comments = informationService.getComments(infoId, page);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (comments != null) {
                            commentAdapter.setData(comments);
                            if (comments.size() < AppConfig.COMMENT_PAGE_SIZE) {
                                lvComments.setPullLoadEnable(false);
                            } else {
                                lvComments.setPullLoadEnable(true);
                            }
                        } else {
                            commentAdapter.setData(new ArrayList<InformationComment>());
                            lvComments.setPullLoadEnable(false);
                        }
                        lvComments.stopRefresh();
                    }
                });
            }
        });
    }

    @Override
    public void onLoadMore() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                if (infoId < 0) {
                    return;
                }
                final List<InformationComment> comments1 = informationService.getComments(infoId, ++page);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (comments1 != null) {
                            comments.addAll(comments1);
                            commentAdapter.setData(comments);
                            if (comments1.size() < AppConfig.COMMENT_PAGE_SIZE) {
                                lvComments.setPullLoadEnable(false);
                            } else {
                                lvComments.setPullLoadEnable(true);
                            }
                        } else {
                            page--;
                            lvComments.setPullLoadEnable(false);
                        }
                        lvComments.stopLoadMore();
                    }
                });
            }
        });
    }

    /**
     * 初始化界面
     */
    private void intiView() {
        setTvTitle("资讯详情");

        setRightIcon(R.mipmap.app_share);
        root = (RelativeLayout) findViewById(R.id.rl_information);
        scInfo = (ScrollView) findViewById(R.id.sc_information);

        tvTitle = (TextView) findViewById(R.id.tv_information_detail_title);
        tvFrom = (TextView) findViewById(R.id.tv_information_detail_from);
        tvTime = (TextView) findViewById(R.id.tv_information_detail_time);
        tvPraise = (TextView) findViewById(R.id.tv_information_detail_praise);
        tvDisPraise = (TextView) findViewById(R.id.tv_information_detail_dispraise);
        llInfo = (LinearLayout) findViewById(R.id.ll_edit_information);
        /**
         * 监听键盘状态，改变输入框的位置
         */
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 200) {
                    if (!inputIsShowing) {
                        Message message = new Message();
                        message.what = IPUT_SHOW;
                        message.arg1 = rootInvisibleHeight;
                        handler.sendMessage(message);
                        inputIsShowing = true;
                    }
                } else {
                    //键盘隐藏
                    if (inputIsShowing) {
                        handler.sendEmptyMessage(IPUT_DISMISS);
                        inputIsShowing = false;
                    }
                }
            }
        });

        wbContent = (WebView) findViewById(R.id.wb_information_detail_content);
        wbContent.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

        });

        WebSettings webSettings = wbContent.getSettings(); // webView: 类WebView的实例
//        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
//        webSettings.setBlockNetworkImage(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);  //就是这句
        //禁止
        wbContent.setVerticalScrollBarEnabled(false);
        wbContent.setVerticalScrollbarOverlay(false);
        wbContent.setHorizontalScrollBarEnabled(false);
        wbContent.setHorizontalScrollbarOverlay(false);

        wbContent.getSettings().setDefaultTextEncodingName("utf-8");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            wbContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            wbContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }

        etCConetent = (EditText) findViewById(R.id.et_information_detail_comment_content);
        btnSend = (Button) findViewById(R.id.btn_information_detail_comment_send);
        ivCollect = (CheckBox) findViewById(R.id.iv_information_detail_collect);
        lvComments = (ScrollXListView) findViewById(R.id.lv_information_detail_comments);
        lvComments.setPullLoadEnable(false);
        lvComments.setPullRefreshEnable(false);
        lvComments.setVerticalScrollBarEnabled(false);
        lvComments.setXListViewListener(this);

        commentAdapter = new ItemInformationCommentAdapter(InformationDetailActivity.this, comments);
        commentAdapter.setInformationCommentListener(new ItemInformationCommentAdapter.InformationCommentListener() {
            @Override
            public void clickHead(int userId) {
                UIHelper.ToastMessage(InformationDetailActivity.this, String.valueOf(userId));
            }
        });
        lvComments.setAdapter(commentAdapter);

        disPraiseSelected = getResources().getDrawable(R.mipmap.information_dispraise_selected);
        disPraiseSelected.setBounds(0, 0, disPraiseSelected.getMinimumWidth(), disPraiseSelected.getMinimumHeight());
        disPraiseNormal = getResources().getDrawable(R.mipmap.information_dispraise_normal);
        disPraiseNormal.setBounds(0, 0, disPraiseNormal.getMinimumWidth(), disPraiseNormal.getMinimumHeight());
        praiseSelected = getResources().getDrawable(R.mipmap.information_praise_selected);
        praiseSelected.setBounds(0, 0, praiseSelected.getMinimumWidth(), praiseSelected.getMinimumHeight());
        praiseNormal = getResources().getDrawable(R.mipmap.information_praise_normal);
        praiseNormal.setBounds(0, 0, praiseNormal.getMinimumWidth(), praiseNormal.getMinimumHeight());
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>html{font-size:18px}img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        btnSend.setOnClickListener(this);
        ivCollect.setOnClickListener(this);
        lvComments.setOnItemClickListener(this);
        lvComments.setOnItemLongClickListener(this);

        tvPraise.setOnClickListener(this);
        tvDisPraise.setOnClickListener(this);

    }

    @Override
    public void rightOperation() {
        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
        mController.openShare(InformationDetailActivity.this, false);


        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                informationService.share(infoId);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 1) return;
        toUserId = comments.get(position - 1).getUser_id();
        if (toUserId == AppContext.getInstance().getUserId()) {
            return;
        }
        Message msg = new Message();
        msg.what = CLICK_COMMENT;
        msg.obj = comments.get(position - 1).getUser_name();
        handler.sendMessage(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_information_detail_comment_send:
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(InformationDetailActivity.this);
                    return;
                }

                if (!etCConetent.getText().toString().startsWith("@")) {
                    toUserId = 0;
                }
                if (TextUtils.isEmpty(etCConetent.getText().toString().trim())) {
                    return;
                }
                InputTools.HideKeyboard(etCConetent);
                btnSend.setClickable(false);
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        final boolean b = informationService.doCommentToUser(infoId, toUserId, etCConetent.getText().toString().trim());
                        onRefresh();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!b) {
                                    UIHelper.ToastMessage(InformationDetailActivity.this, "回复失败");
                                } else {
                                    etCConetent.setText("");
                                }
                                btnSend.setClickable(true);
                            }
                        });
                    }
                });

                break;
            case R.id.tv_information_detail_praise:
                //点赞
                tvDisPraise.setCompoundDrawables(disPraiseNormal, null, null, null);
                tvPraise.setCompoundDrawables(praiseSelected, null, null, null);
                if (information != null) {
                    tvPraise.setText(information.getGrates() + 1 + "");
                    tvDisPraise.setText(information.getUseless() + "");
                    tvPraise.setTextColor(Color.RED);
                    tvDisPraise.setTextColor(Color.parseColor("#808080"));
                }
                praiseAction = 0;
                break;
            case R.id.tv_information_detail_dispraise:
                //点道赞
                tvDisPraise.setCompoundDrawables(disPraiseSelected, null, null, null);
                tvPraise.setCompoundDrawables(praiseNormal, null, null, null);
                if (information != null) {
                    tvPraise.setText(information.getGrates() + "");
                    tvDisPraise.setText(information.getUseless() + 1 + "");

                    tvDisPraise.setTextColor(Color.RED);
                    tvPraise.setTextColor(Color.parseColor("#808080"));
                }
                praiseAction = 1;
                break;
            case R.id.iv_information_detail_collect:
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(InformationDetailActivity.this);
                    return;
                }
                //收藏、取消收藏
                ivCollect.setClickable(false);
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        final boolean res = informationService.collect(infoId, ivCollect.isChecked());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (res)
                                    UIHelper.ToastMessage(InformationDetailActivity.this, "收藏成功");
                                else {
                                    UIHelper.ToastMessage(InformationDetailActivity.this, "收藏失败");
                                }
                                ivCollect.setClickable(true);
                            }
                        });
                    }
                });
                break;
        }
    }

    private int praiseAction = -1;

    @Override
    public void onPause() {
        if (praiseAction == 0 || praiseAction == 1) {
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    informationService.praise(infoId, praiseAction == 0);
                }
            });
        }
        super.onPause();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        return false;
    }
}
